<template>
  <div class="customer-unified-form">
    <!-- 页面顶部导航区 -->
    <div class="form-header">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="page-breadcrumb">
        <el-breadcrumb-item>
          <el-button text @click="goBack" :icon="ArrowLeft">返回</el-button>
        </el-breadcrumb-item>
        <el-breadcrumb-item>客户档案管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ isEdit ? '编辑客户信息' : '新建客户档案' }}</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题和状态 -->
      <div class="page-title-section">
        <div class="title-info">
          <h1 class="page-title">
            {{ isEdit ? `编辑客户：${formData.basicInfo.customerName}` : '新建客户档案' }}
          </h1>
          <el-tag v-if="isEdit" :type="getStatusTagType(formData.basicInfo.customerStatus)" size="large">
            {{ formData.basicInfo.customerStatus }}
          </el-tag>
        </div>
        
        <!-- 快速操作按钮 -->
        <div class="header-actions">
          <el-button @click="saveDraft" :loading="draftSaving">
            <el-icon><Document /></el-icon>
            保存草稿
          </el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '保存修改' : '创建客户' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 信息完整度进度指示器 -->
    <div class="completion-progress">
      <div class="progress-header">
        <span class="progress-label">信息完整度</span>
        <span class="progress-percentage">{{ completionPercentage }}%</span>
      </div>
      
      <el-progress 
        :percentage="completionPercentage" 
        :color="getProgressColor(completionPercentage)"
        :show-text="false"
        class="completion-bar"
      />
      
      <div class="completion-breakdown">
        <div class="breakdown-item" v-for="section in completionSections" :key="section.key">
          <el-icon :class="{ completed: section.completed, warning: section.hasWarnings }">
            <component :is="section.completed ? 'CircleCheck' : 'CirclePlus'" />
          </el-icon>
          <span class="section-name">{{ section.name }}</span>
          <span class="section-status">{{ section.status }}</span>
        </div>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="form-container">
      <!-- 主表单区域 -->
      <div class="main-form-area">
        <!-- 1. 基础信息模块 -->
        <BasicInfoSection 
          v-model:form-data="formData.basicInfo"
          v-model:contact-info="formData.contactInfo"
          v-model:social-info="formData.socialInfo"
          @validation-change="onBasicInfoValidation"
        />

        <!-- 2. 旅游偏好模块 -->
        <TravelPreferencesSection 
          v-model:form-data="formData.travelPreferences"
          @validation-change="onTravelPreferencesValidation"
        />

        <!-- 3. 健康信息模块 -->
        <HealthInfoSection 
          v-model:form-data="formData.healthInfo"
          @validation-change="onHealthInfoValidation"
        />

        <!-- 4. 家庭社交信息模块 -->
        <FamilyInfoSection 
          v-model:form-data="formData.familyInfo"
          @validation-change="onFamilyInfoValidation"
        />
      </div>

      <!-- 右侧辅助信息区域 -->
      <div class="sidebar-area">
        <!-- 填写进度提示 -->
        <ProgressCard 
          :overall-progress="completionPercentage"
          :progress-sections="progressSections"
          :next-steps="nextSteps"
        />

        <!-- 智能推荐建议 -->
        <RecommendationCard 
          :age-based-recommendations="ageBasedRecommendations"
          :health-based-recommendations="healthBasedRecommendations"
          :fill-tips="fillTips"
          @apply-recommendation="applyRecommendation"
        />

        <!-- 操作历史记录 -->
        <HistoryCard 
          :operation-history="operationHistory"
        />
      </div>
    </div>

    <!-- 底部固定操作栏 -->
    <div class="form-footer">
      <div class="footer-content">
        <div class="footer-left">
          <el-button @click="resetForm" :disabled="submitting">
            <el-icon><RefreshLeft /></el-icon>
            重置表单
          </el-button>
          <el-button @click="goBack" :disabled="submitting">
            <el-icon><ArrowLeft /></el-icon>
            取消
          </el-button>
        </div>

        <div class="footer-center">
          <div class="validation-summary" v-if="validationErrors.length > 0">
            <el-icon color="red"><Warning /></el-icon>
            <span>还有 {{ validationErrors.length }} 项必填信息需要完善</span>
            <el-button text type="primary" @click="showValidationDetails">
              查看详情
            </el-button>
          </div>
          <div class="validation-success" v-else>
            <el-icon color="green"><CircleCheck /></el-icon>
            <span>所有必填信息已完善，可以提交</span>
          </div>
        </div>

        <div class="footer-right">
          <el-button @click="saveDraft" :loading="draftSaving" :disabled="submitting">
            <el-icon><Document /></el-icon>
            保存草稿
          </el-button>
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitting"
            :disabled="validationErrors.length > 0"
          >
            <el-icon><Check /></el-icon>
            {{ isEdit ? '保存修改' : '创建客户' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Check, Document, RefreshLeft, Warning, CircleCheck, Plus as CirclePlus 
} from '@element-plus/icons-vue'

// 导入子组件
import BasicInfoSection from './components/BasicInfoSection.vue'
import TravelPreferencesSection from './components/TravelPreferencesSection.vue'
import HealthInfoSection from './components/HealthInfoSection.vue'
import FamilyInfoSection from './components/FamilyInfoSection.vue'
import ProgressCard from './components/ProgressCard.vue'
import RecommendationCard from './components/RecommendationCard.vue'
import HistoryCard from './components/HistoryCard.vue'

// API
import customerAPI from '@/api/customer'

const router = useRouter()
const route = useRoute()

// 页面状态
const isEdit = computed(() => !!route.params.id)
const submitting = ref(false)
const draftSaving = ref(false)
const hasUnsavedChanges = ref(false)

// 表单数据
const formData = reactive({
  basicInfo: {
    customerName: '',
    gender: '',
    birthDate: '',
    idCard: '',
    customerStatus: '潜在客户'
  },
  contactInfo: {
    primaryPhone: '',
    backupPhone: '',
    wechat: '',
    qq: '',
    email: '',
    addressRegion: [],
    detailAddress: '',
    postalCode: ''
  },
  socialInfo: {
    emergencyContactName: '',
    emergencyContactRelation: '',
    emergencyContactPhone: '',
    workStatus: '',
    occupation: ''
  },
  travelPreferences: {
    budget: {
      budgetRange: '',
      consumptionFeatures: [],
      paymentPreference: ''
    },
    destinations: {
      domesticRegions: [],
      internationalRegions: [],
      landscapePreferences: [],
      climatePreferences: []
    }
  },
  healthInfo: {
    healthStatus: '',
    mobilityAbility: '',
    details: {
      cardiovascularDiseases: [],
      endocrineDiseases: [],
      respiratoryDiseases: [],
      musculoskeletalDiseases: [],
      otherDiseases: '',
      medicationInfo: '',
      dietaryRestrictions: [],
      insuranceInfo: ''
    }
  },
  familyInfo: {
    maritalStatus: '',
    spouseInfo: {
      spouseName: '',
      spousePhone: '',
      spouseAge: null,
      spouseTravelTogether: ''
    },
    childrenInfo: [],
    decision: {
      decisionPattern: '',
      influenceFactors: []
    }
  }
})

// 验证状态
const validationErrors = ref([])
const validationStates = reactive({
  basicInfo: { valid: false, errors: [] },
  travelPreferences: { valid: false, errors: [] },
  healthInfo: { valid: false, errors: [] },
  familyInfo: { valid: false, errors: [] }
})

// 完整度计算
const completionPercentage = computed(() => {
  const sections = completionSections.value
  const totalWeight = sections.reduce((sum, section) => sum + section.weight, 0)
  const completedWeight = sections.reduce((sum, section) => {
    return sum + (section.completed ? section.weight : section.percentage * section.weight / 100)
  }, 0)
  
  return Math.round(completedWeight / totalWeight * 100)
})

const completionSections = computed(() => {
  return [
    {
      key: 'basicInfo',
      name: '基础信息',
      weight: 30,
      completed: calculateBasicInfoCompletion() === 100,
      percentage: calculateBasicInfoCompletion(),
      status: calculateBasicInfoCompletion() === 100 ? '已完成' : '需要完善',
      hasWarnings: validationStates.basicInfo.errors.length > 0
    },
    {
      key: 'travelPreferences',
      name: '旅游偏好',
      weight: 25,
      completed: calculateTravelPreferencesCompletion() === 100,
      percentage: calculateTravelPreferencesCompletion(),
      status: calculateTravelPreferencesCompletion() === 100 ? '已完成' : '可选填写',
      hasWarnings: false
    },
    {
      key: 'healthInfo',
      name: '健康信息',
      weight: 25,
      completed: calculateHealthInfoCompletion() === 100,
      percentage: calculateHealthInfoCompletion(),
      status: calculateHealthInfoCompletion() === 100 ? '已完成' : '建议填写',
      hasWarnings: validationStates.healthInfo.errors.length > 0
    },
    {
      key: 'familyInfo',
      name: '家庭社交',
      weight: 20,
      completed: calculateFamilyInfoCompletion() === 100,
      percentage: calculateFamilyInfoCompletion(),
      status: calculateFamilyInfoCompletion() === 100 ? '已完成' : '可选填写',
      hasWarnings: false
    }
  ]
})

// 进度相关计算
const progressSections = computed(() => completionSections.value)

const nextSteps = computed(() => {
  const steps = []
  const sections = completionSections.value
  
  sections.forEach(section => {
    if (!section.completed) {
      if (section.key === 'basicInfo') {
        steps.push('完善基础信息（必填）')
      } else if (section.percentage < 50) {
        steps.push(`补充${section.name}信息`)
      }
    }
  })
  
  return steps.slice(0, 3) // 最多显示3个建议
})

// 智能推荐
const ageBasedRecommendations = computed(() => {
  const age = calculateAge(formData.basicInfo.birthDate)
  const recommendations = []
  
  if (age >= 65) {
    recommendations.push({
      type: 'budget',
      title: '建议选择舒适型预算',
      description: '适合年龄的舒适出行体验',
      icon: 'Money'
    })
    
    recommendations.push({
      type: 'destination',
      title: '推荐温泉康养目的地',
      description: '有益身心健康的旅游方式',
      icon: 'FirstAidKit'
    })
  }
  
  return recommendations
})

const healthBasedRecommendations = computed(() => {
  const recommendations = []
  
  if (formData.healthInfo.healthStatus === '健康较差' || formData.healthInfo.healthStatus === '健康很差') {
    recommendations.push({
      type: 'health',
      title: '建议选择短途旅行',
      description: '避免长途旅行对身体造成负担'
    })
  }
  
  return recommendations
})

const fillTips = computed(() => {
  const tips = []
  
  if (!formData.basicInfo.customerName) {
    tips.push({
      type: 'required',
      title: '请填写客户姓名',
      description: '客户姓名是必填项目',
      alertType: 'error'
    })
  }
  
  if (!formData.contactInfo.primaryPhone) {
    tips.push({
      type: 'required',
      title: '请填写主要手机号',
      description: '主要手机号是联系客户的重要方式',
      alertType: 'error'
    })
  }
  
  return tips
})

// 操作历史
const operationHistory = ref([
  {
    time: '2025-01-26 14:30',
    action: '创建客户档案',
    operator: '当前用户'
  }
])

// 自动保存相关
const autosaveInterval = ref(null)
const lastSaveTime = ref(null)

// 方法定义
const goBack = () => {
  if (hasUnsavedChanges.value) {
    ElMessageBox.confirm('存在未保存的修改，确定要离开吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.go(-1)
    })
  } else {
    router.go(-1)
  }
}

const getStatusTagType = (status) => {
  const typeMap = {
    '有效客户': 'success',
    '潜在客户': 'primary',
    '无效客户': 'info',
    '已成交客户': 'warning',
    '黑名单': 'danger'
  }
  return typeMap[status] || 'info'
}

const getProgressColor = (percentage) => {
  if (percentage < 30) return '#ff4d4f'
  if (percentage < 60) return '#faad14'
  if (percentage < 90) return '#1890ff'
  return '#52c41a'
}

const calculateAge = (birthDate) => {
  if (!birthDate) return 0
  const today = new Date()
  const birth = new Date(birthDate)
  let age = today.getFullYear() - birth.getFullYear()
  const monthDiff = today.getMonth() - birth.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  
  return age
}

// 完整度计算函数
const calculateBasicInfoCompletion = () => {
  const required = ['customerName', 'gender', 'birthDate', 'idCard']
  const optional = ['primaryPhone']
  
  let score = 0
  const totalFields = required.length + optional.length
  
  required.forEach(field => {
    if (formData.basicInfo[field] || formData.contactInfo[field]) {
      score += 1
    }
  })
  
  optional.forEach(field => {
    if (formData.contactInfo[field]) {
      score += 1
    }
  })
  
  return Math.round(score / totalFields * 100)
}

const calculateTravelPreferencesCompletion = () => {
  let score = 0
  let total = 4
  
  if (formData.travelPreferences.budget.budgetRange) score++
  if (formData.travelPreferences.destinations.domesticRegions.length > 0) score++
  if (formData.travelPreferences.destinations.landscapePreferences.length > 0) score++
  if (formData.travelPreferences.budget.paymentPreference) score++
  
  return Math.round(score / total * 100)
}

const calculateHealthInfoCompletion = () => {
  let score = 0
  let total = 3
  
  if (formData.healthInfo.healthStatus) score++
  if (formData.healthInfo.mobilityAbility) score++
  if (formData.healthInfo.details.dietaryRestrictions.length > 0) score++
  
  return Math.round(score / total * 100)
}

const calculateFamilyInfoCompletion = () => {
  let score = 0
  let total = 2
  
  if (formData.familyInfo.maritalStatus) score++
  if (formData.familyInfo.decision.decisionPattern) score++
  
  return Math.round(score / total * 100)
}

// 验证处理
const onBasicInfoValidation = (validation) => {
  validationStates.basicInfo = validation
  updateValidationErrors()
}

const onTravelPreferencesValidation = (validation) => {
  validationStates.travelPreferences = validation
  updateValidationErrors()
}

const onHealthInfoValidation = (validation) => {
  validationStates.healthInfo = validation
  updateValidationErrors()
}

const onFamilyInfoValidation = (validation) => {
  validationStates.familyInfo = validation
  updateValidationErrors()
}

const updateValidationErrors = () => {
  const allErrors = []
  Object.values(validationStates).forEach(state => {
    allErrors.push(...state.errors)
  })
  validationErrors.value = allErrors
}

const showValidationDetails = () => {
  const errorList = validationErrors.value.map(error => `• ${error}`).join('\n')
  ElMessageBox.alert(errorList, '需要完善的信息', {
    confirmButtonText: '我知道了'
  })
}

// 保存和提交
const saveDraft = async () => {
  try {
    draftSaving.value = true
    const draftData = {
      ...formData,
      lastModified: new Date().toISOString(),
      completionPercentage: completionPercentage.value
    }
    
    localStorage.setItem(`customer-draft-${route.params.id || 'new'}`, JSON.stringify(draftData))
    lastSaveTime.value = new Date()
    hasUnsavedChanges.value = false
    
    ElMessage.success('草稿已保存')
  } catch (error) {
    ElMessage.error('草稿保存失败')
  } finally {
    draftSaving.value = false
  }
}

const submitForm = async () => {
  if (validationErrors.value.length > 0) {
    showValidationDetails()
    return
  }
  
  try {
    submitting.value = true
    
    if (isEdit.value) {
      await customerAPI.update(route.params.id, formData)
      ElMessage.success('客户信息更新成功')
    } else {
      await customerAPI.create(formData)
      ElMessage.success('客户档案创建成功')
    }
    
    hasUnsavedChanges.value = false
    router.push('/customers')
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？所有填写的信息将被清空。', '确认重置', {
    confirmButtonText: '确定重置',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 重置表单数据
    Object.keys(formData).forEach(key => {
      if (typeof formData[key] === 'object') {
        Object.keys(formData[key]).forEach(subKey => {
          if (Array.isArray(formData[key][subKey])) {
            formData[key][subKey] = []
          } else if (typeof formData[key][subKey] === 'object') {
            Object.keys(formData[key][subKey]).forEach(subSubKey => {
              formData[key][subKey][subSubKey] = Array.isArray(formData[key][subKey][subSubKey]) ? [] : ''
            })
          } else {
            formData[key][subKey] = ''
          }
        })
      } else {
        formData[key] = ''
      }
    })
    
    ElMessage.success('表单已重置')
  })
}

const applyRecommendation = (recommendation) => {
  if (recommendation.type === 'budget') {
    formData.travelPreferences.budget.budgetRange = '舒适型'
    ElMessage.success('已应用预算推荐')
  } else if (recommendation.type === 'destination') {
    if (!formData.travelPreferences.destinations.landscapePreferences.includes('温泉养生')) {
      formData.travelPreferences.destinations.landscapePreferences.push('温泉养生')
    }
    ElMessage.success('已应用目的地推荐')
  }
}

// 自动保存
const enableAutosave = () => {
  autosaveInterval.value = setInterval(() => {
    if (hasUnsavedChanges.value) {
      saveDraft()
    }
  }, 30000) // 每30秒自动保存
}

// 监听表单变化
watch(formData, () => {
  hasUnsavedChanges.value = true
}, { deep: true })

// 生命周期
onMounted(async () => {
  if (isEdit.value) {
    try {
      const response = await customerAPI.getDetail(route.params.id)
      Object.assign(formData, response.data)
    } catch (error) {
      ElMessage.error('加载客户信息失败')
    }
  } else {
    // 尝试恢复草稿
    const draftData = localStorage.getItem('customer-draft-new')
    if (draftData) {
      try {
        const draft = JSON.parse(draftData)
        Object.assign(formData, draft)
        ElMessage.info('已恢复之前的草稿')
      } catch (error) {
        console.error('恢复草稿失败:', error)
      }
    }
  }
  
  enableAutosave()
})

onUnmounted(() => {
  if (autosaveInterval.value) {
    clearInterval(autosaveInterval.value)
  }
})

// 页面离开确认
window.addEventListener('beforeunload', (e) => {
  if (hasUnsavedChanges.value) {
    e.preventDefault()
    e.returnValue = ''
  }
})
</script>

<style lang="scss" scoped>
/* 客户表单页面专用样式变量 */
:root {
  /* 主色调 */
  --form-primary: #007AFF;
  --form-success: #34C759;
  --form-warning: #FF9500;
  --form-danger: #FF3B30;
  --form-info: #5AC8FA;
  
  /* 背景色 */
  --form-bg: #F2F2F7;
  --form-card-bg: #FFFFFF;
  --form-section-bg: #FAFAFA;
  
  /* 文字颜色 */
  --form-text-primary: #000000;
  --form-text-secondary: #3C3C43;
  --form-text-tertiary: #8E8E93;
  
  /* 边框颜色 */
  --form-border-light: #E5E5EA;
  --form-border-medium: #D1D1D6;
  
  /* 阴影 */
  --form-shadow-light: 0 1px 3px rgba(0,0,0,0.1);
  --form-shadow-medium: 0 4px 12px rgba(0,0,0,0.15);
}

/* 整体布局样式 */
.customer-unified-form {
  min-height: 100vh;
  background: var(--form-bg);
  
  .form-header {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid var(--form-border-light);
    position: sticky;
    top: 0;
    z-index: 100;
    
    .page-breadcrumb {
      margin-bottom: 12px;
    }
    
    .page-title-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title-info {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .page-title {
          font-size: 24px;
          font-weight: 600;
          color: var(--form-text-primary);
          margin: 0;
        }
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .completion-progress {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid var(--form-border-light);
    
    .progress-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .progress-label {
        font-size: 14px;
        color: var(--form-text-secondary);
      }
      
      .progress-percentage {
        font-size: 16px;
        font-weight: 600;
        color: var(--form-primary);
      }
    }
    
    .completion-bar {
      margin-bottom: 16px;
    }
    
    .completion-breakdown {
      display: flex;
      gap: 24px;
      
      .breakdown-item {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 16px;
          
          &.completed {
            color: var(--form-success);
          }
          
          &.warning {
            color: var(--form-warning);
          }
        }
        
        .section-name {
          font-size: 14px;
          color: var(--form-text-primary);
        }
        
        .section-status {
          font-size: 12px;
          color: var(--form-text-tertiary);
        }
      }
    }
  }
  
  .form-container {
    display: flex;
    gap: 24px;
    max-width: 1400px;
    margin: 0 auto;
    padding: 24px;
    
    .main-form-area {
      flex: 1;
      min-width: 0;
    }
    
    .sidebar-area {
      width: 320px;
      flex-shrink: 0;
    }
  }
  
  .form-footer {
    background: white;
    border-top: 1px solid var(--form-border-light);
    padding: 16px 24px;
    position: sticky;
    bottom: 0;
    z-index: 100;
    
    .footer-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      max-width: 1400px;
      margin: 0 auto;
      
      .footer-left,
      .footer-right {
        display: flex;
        gap: 12px;
      }
      
      .footer-center {
        .validation-summary,
        .validation-success {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
        }
      }
    }
  }
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .customer-unified-form .form-container {
    flex-direction: column;
    
    .sidebar-area {
      width: 100%;
      order: -1;
    }
  }
}

@media (max-width: 768px) {
  .customer-unified-form {
    .form-header {
      padding: 12px 16px;
      
      .page-title-section {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        
        .title-info .page-title {
          font-size: 20px;
        }
        
        .header-actions {
          width: 100%;
          justify-content: flex-end;
        }
      }
    }
    
    .completion-progress {
      padding: 12px 16px;
      
      .completion-breakdown {
        flex-direction: column;
        gap: 12px;
      }
    }
    
    .form-container {
      padding: 16px;
      gap: 16px;
    }
    
    .form-footer {
      padding: 12px 16px;
      
      .footer-content {
        flex-direction: column;
        gap: 12px;
        
        .footer-left,
        .footer-right {
          width: 100%;
          justify-content: center;
        }
        
        .footer-center {
          order: -1;
        }
      }
    }
  }
}
</style>